package com.gopay.common.cipher.utils;

import com.gopay.common.cipher.vo.SecurityInfoKeyBox;
import com.gopay.common.util.SerializeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 对redis中的简单操作，只提供给密钥管理使用
 * Created by zyt on 2017/4/18.
 */
public class CacheUtils {
    private static final Logger logger = LoggerFactory.getLogger(CacheUtils.class);

    //配置文件名
    private static final String PROPERTIES_FILE = "cipher.properties";
    //集群地址在配置文件中的key
    private static final String REDIS_CLUSTER_HOSTANDPORT_KEY = "redis.cluster.hostandport";
    //集群超时时间在配置文件中的key
    private static final String REDIS_CLUSTER_TIMEOUT_KEY = "redis.cluster.timeout";
    //集群重定向次数在配置文件中的key
    private static final String REDIS_CLUSTER_MAXREDIRECTIONS_KEY = "redis.cluster.maxredirections";

    //集群地址
    private static String REDIS_CLUSTER_HOSTANDPORT;
    //集群超时时间，默认1s
    private static int REDIS_CLUSTER_TIMEOUT = 1000;
    //集群重定向次数，默认5次
    private static int REDIS_CLUSTER_MAXREDIRECTIONS = 5;

    private static JedisCluster jedisCluster;
    //检测结果--正常
    public static final String NORMAL_FLAG = "normal";
    //检测结果--异常
    public static final String ABNORMAL_FLAG = "abnormal";

    //redis状态，暂时只在启动时候检测
    private static String redisStatus = "";
    //配置文件状态
    private static String propStatus = "";

    /**
     * 向名称为channel_key的string中添加一个对象
     * @param key
     * @param o
     */
    public static void setObject(String key ,Object o){
        if(jedisCluster == null){
            initialCluster();
        }
        logger.error("set or modify key :" + key);
        jedisCluster.set(key.getBytes(), SerializeUtil.serialize(o));
    }

    /**
     * 获取名称为key的对象
     * @param key
     * @return
     */
    public static  Object getObject(String key){
        try {
            if(jedisCluster == null){
                initialCluster();
            }
            byte[] bytes = jedisCluster.get(key.getBytes());
            return SerializeUtil.unserialize(bytes);
        } catch(Exception e){
            logger.error("从redis获取密钥失败：", e);
            return null;
        }
    }

    /**
     * 初始化redis集群
     */
    private static void initialCluster() {
        if(StringUtils.isBlank(REDIS_CLUSTER_HOSTANDPORT)){
            initParams();
        }
        logger.info("redis cluster initialing...");
        Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();
        logger.error("================>" + REDIS_CLUSTER_HOSTANDPORT);

        if(!StringUtils.isEmpty(REDIS_CLUSTER_HOSTANDPORT)){
            if(REDIS_CLUSTER_HOSTANDPORT.contains(",")){
                String[] hps = REDIS_CLUSTER_HOSTANDPORT.split(",");
                for(String hp : hps){
                    addNodes2Cluster(jedisClusterNodes, hp);
                }
            }else{
                addNodes2Cluster(jedisClusterNodes, REDIS_CLUSTER_HOSTANDPORT);
            }
        }else{
            logger.error("=====>未获取到集群配置信息：" + REDIS_CLUSTER_HOSTANDPORT);
        }
        jedisCluster = new JedisCluster(jedisClusterNodes, REDIS_CLUSTER_TIMEOUT, REDIS_CLUSTER_MAXREDIRECTIONS);

        logger.info("redis cluster initialed...");
    }

    /**
     * 添加节点到集群中
     * @param jedisClusterNodes
     * @param source
     */
    private static void addNodes2Cluster(Set<HostAndPort> jedisClusterNodes,String source) {
        String[] hps = source.split(":");
        String host = hps[0];
        int port = Integer.valueOf(hps[1]).intValue();
        jedisClusterNodes.add(new HostAndPort(host, port));
    }

    /**
     *
     * @Description: 根据配置文件，初始化连接的一些参数
     * @author zyt
     */
    private static void initParams(){
        InputStream inputstream = CacheUtils.class.getClassLoader().getResourceAsStream(PROPERTIES_FILE);
        Properties pathConfig = new Properties();
        try {
            pathConfig.load(inputstream);
            REDIS_CLUSTER_HOSTANDPORT = pathConfig.getProperty(REDIS_CLUSTER_HOSTANDPORT_KEY);
            String timeOut = pathConfig.getProperty(REDIS_CLUSTER_TIMEOUT_KEY);
            String maxRedirections = pathConfig.getProperty(REDIS_CLUSTER_MAXREDIRECTIONS_KEY);
            if(StringUtils.isNotBlank(timeOut) && StringUtils.isNumeric(timeOut)){
                REDIS_CLUSTER_TIMEOUT = Integer.parseInt(timeOut);
            }
            if(StringUtils.isNotBlank(maxRedirections) && StringUtils.isNumeric(maxRedirections)){
                REDIS_CLUSTER_MAXREDIRECTIONS = Integer.parseInt(maxRedirections);
            }
            inputstream.close();
        } catch (IOException e) {
            logger.error("读取Cipher配置文件失败:" , e);
        }
    }

    /**
     *  检测项目中是否有密钥相关（redis）配置文件，以及配置是否齐全
     * @return  正确：true； 不正确：false
     */
    public static boolean checkCacheProp(){
        if(StringUtils.isBlank(propStatus)) {
            if (!isPropFileExist()) {
                logger.error("Load cipher.properties failed,perhaps this project don't need cipher function, or lost this properties");
                propStatus = ABNORMAL_FLAG;
            } else {
                InputStream inputstream = CacheUtils.class.getClassLoader().getResourceAsStream(PROPERTIES_FILE);
                Properties pathConfig = new Properties();
                try {
                    pathConfig.load(inputstream);
                    if (!pathConfig.containsKey(REDIS_CLUSTER_HOSTANDPORT_KEY)
                            || !pathConfig.containsKey(DataKeyUtils.KEY_NAME)) {
                        logger.error("miss key: {} in {}, redis will not use in cipher", REDIS_CLUSTER_HOSTANDPORT_KEY, PROPERTIES_FILE);
                        propStatus = ABNORMAL_FLAG;
                    } else {
                        propStatus = NORMAL_FLAG;
                    }
                    inputstream.close();
                } catch (IOException e) {
                    propStatus = ABNORMAL_FLAG;
                    logger.error("读取Cipher配置文件失败:", e);
                }
            }
        }
        return StringUtils.equals(propStatus, NORMAL_FLAG);
    }

    public static boolean isPropFileExist(){
        URL propUrl = CacheUtils.class.getClassLoader().getResource(PROPERTIES_FILE);
        if(propUrl == null){
            return false;
        } else {
            File f = new File(propUrl.getPath());
            if (!f.exists()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检测当前redis是否正常
     * @return 正常：true；异常：false
     */
    public static boolean checkCacheConncetion() {
        //if (StringUtils.isBlank(redisStatus)) {}
        initialCluster();
        if (jedisCluster != null) {
            try {
                jedisCluster.echo("test");
                redisStatus = NORMAL_FLAG;
            } catch (Exception e) {
                redisStatus = ABNORMAL_FLAG;
                logger.error("Redis connection exception,thie server will cipher without redis:", e);
            }
        } else {
            redisStatus = ABNORMAL_FLAG;
        }

        return StringUtils.equals(redisStatus, NORMAL_FLAG);
    }

    public static void main(String[] args){
      /*  AtomicInteger cur_fail_num = new AtomicInteger();
        System.out.println(cur_fail_num);
        cur_fail_num.incrementAndGet();
        System.out.println(cur_fail_num);*/
        Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();
        jedisClusterNodes.add(new HostAndPort("223.203.208.120",6379));
        jedisClusterNodes.add(new HostAndPort("223.203.208.121",6379));
        jedisClusterNodes.add(new HostAndPort("223.203.208.122",6379));

        JedisCluster jc = new JedisCluster(jedisClusterNodes, REDIS_CLUSTER_TIMEOUT, 3);
        byte[] bytes = jc.get("securityInfoKeyBox:mer".getBytes());
        //jc.del("securityInfoKeyBox:test_100".getBytes());
        Object obj = SerializeUtil.unserialize(bytes);
        SecurityInfoKeyBox box = (SecurityInfoKeyBox)obj;
        //System.out.println(res);
    }
}
